#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <semaphore.h>
#include <string.h>

#include "mqtt_config.h"
#include "mqtt_log.h"
#include "mqttclient.h"
#include "mqtt_manager.h"
#include "sensor_manager.h"
#include "dht11.h"

static PSensorDevice g_SensorDevs  = NULL;

static void *Sensor_readsend_thread_func (void *arg)
{
	PSensorDevice tpSensorDevice;
    mqtt_client_t *tmpclient = (mqtt_client_t *)arg;
    mqtt_message_t msg;
    memset(&msg, 0, sizeof(msg));
	// int ret;

    mqtt_list_subscribe_topic(client);
	
	while (1)
	{
        // printf("\n%s:%d %s()\n",__FILE__, __LINE__, __FUNCTION__);
        tpSensorDevice = g_SensorDevs;
        while(tpSensorDevice != NULL)
        {
            tpSensorDevice->GetSensorDataEvent();
            msg.payload = (void *) tpSensorDevice->databuf;
            printf("\nname:%s,databuf:%s\n",tpSensorDevice->name,tpSensorDevice->databuf);
            msg.qos = 0;
            mqtt_publish(tmpclient, tpSensorDevice->name, &msg);

            tpSensorDevice = tpSensorDevice->ptNext;
            sleep(2);

            /*根据button结构体内的信息在尾部展示温湿度值 */
        }
        sleep(3);
    }

	return NULL;
}

void SensorDeviceInit(void)
{
    //mqtt_client_t *client = (mqtt_client_t *)arg;
	pthread_t tid;
	
	PSensorDevice ptTmp = g_SensorDevs;
	while (ptTmp)
	{
		/* init device */
        printf("%s:%d %s()\n",__FILE__, __LINE__, __FUNCTION__);
        sleep(5);
		ptTmp->DeviceInit();
		ptTmp= ptTmp->ptNext;
	}
    pthread_create(&tid, NULL, Sensor_readsend_thread_func, client);
}

void RegisterSensorDevice(PSensorDevice ptSensorDev)
{
    ptSensorDev->ptNext = g_SensorDevs;
    g_SensorDevs =  ptSensorDev;
}

void SensorSystemRegister(void)
{
    Dht11DeviceRegister();
}


// int GetSensorDataEvent(PSensorDataEvent ptSensorDataEvent)
// {
//     PSensorDevice temptSensorDevice;
//     temptSensorDevice = g_SensorDevs;
//     while(temptSensorDevice != NULL)
//     {
//         if (strcmp(temptSensorDevice->name,ptSensorDataEvent->name) != 0)
//         {
//             temptSensorDevice->GetSensorDataEvent(ptSensorDataEvent);
//             return 0;
//         }
//         else temptSensorDevice++;
//     }
//     if(temptSensorDevice == NULL)return -1;
// }

//读数线程 读到数据后通过MQTT发布出去 如何做设备区分（重新发布设备主题信息？）
// static void *Sensor_readsend_thread_func (void *data)
// {
// 	PSensorDevice ptSensorDevice = (PSensorDevice)data;
// 	SensorDataEvent tSensorDataEvent;
// 	int ret;
	
// 	while (1)
// 	{
// 		/* 读数据 */
// 		ret = ptSensorDevice->GetSensorDataEvent(&tSensorDataEvent);

// 		if (!ret)
// 		{	
// 			//发送数据 mQTT根据设备名字新建TOPIC 间断发送数据
// 		}
//         sleep(5);
// 	}

// 	return NULL;
// }

